<!DOCTYPE html>
<html lang="en">   
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
	<title>口令红包</title>
</head>
<link rel="stylesheet" href="__CSS__/index.min.css">
<body>
	<audio id="audio" src="" controls style="display: none;">

	</audio>
	<div id="app" v-cloak>
		<div class="top"> 
			<div class="pic" >
				<img :src="boss.headurl" alt="">
			</div>
			<p class="name">{{boss.nickname}}</p> 
			<div>口令说对就奖励你</div>
			<div class="sayPic">
				<img src="__IMAGE__/huatong2.png" alt="">
				"{{boss.commond}}"
			</div>
			<div id="longtap" class="longtap" style="display: none;">
				长按说出以上口令获取奖励
			</div>
			<div class="longtap nothing" v-if="boss.remain_number==0&&idarr.indexOf(userInfo.id)==-1&&boss.status!=4">
				奖励都被领完了
			</div>
			<div class="longtap nothing" v-if="userInfo.id!=undefined&&idarr.indexOf(userInfo.id)!=-1&&boss.status!=4">
				该红包已经抢过了
			</div>
			<!-- 超过24小时 -->
			<div class="longtap nothing" v-if="boss.status==4">
				该红包已经失效
			</div>
			<div class="bottom">
				<div @click="To('{:U('user/withdraw')}')">
					<img src="__IMAGE__/money.png" alt="">
					<span>去提现</span>
				</div>
				<div @click="To('{:U('red/send')}')">
					<img src="__IMAGE__/huatong.png" alt="">
					<span>我也发一个</span>
				</div>
				<div @click="share">
					<img src="__IMAGE__/share.png" alt="">
					<span>告诉好友</span>
				</div>
			</div>
		</div>
		<div class="tuwen" v-if="boss.type==2">
			<a :href="boss.url"><img :src="boss.image" alt="图片加载中..."></a>
			<p>{{boss.content}}</p>
		</div>
		<div class="detail">
			<p class="totalMoney" v-if="isBoss">共1.00元，领取0/1，剩余1.00元</p>
			<p class="totalMoney" v-if="!isBoss">领取{{boss.number - boss.remain_number}}/{{boss.number}}个</p>			
			<div class="message" v-for="(vo,index) in redInfo">
				<div class="m_left">
					<div>
						<img :src="vo.headurl" alt="">
					</div>
					<div>
						<p class="sayName">{{vo.nickname}}</p>
						<div class="sayTime" @click="toSay(vo.file_path)">
							{{vo.second | str(vo.second)}}
						</div>
					</div>
				</div>
				<div class="m_right">	
					<p class="price">{{vo.money | toFixed(vo.money)}}元</p>
					<p>{{vo.add_time | time(vo.add_time)}}</p>
				</div>
			</div>
		</div>
		<div class="box" v-if="flag">
			<img src="__IMAGE__/timg.gif" alt="">
		</div>
		<div class="box2" v-if="flag2" @click="flag2=false">
			<img src="__IMAGE__/bigshare.png" alt="">
		</div>
		<div class="clear" v-if="flag3">
			{{text}}
		</div>
	</div>
	<script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
	<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
	<script src="__JS__/common.min.js"></script>
	<script src="__JS__/vue.min.js"></script>
	<script src="__JS__/index.min.js"></script>
	<script>
		var app = new Vue({
			el: "#app",
			data: {
				nothing: false,
				isBoss: false,
				flag: false,	//录音图标
				flag2: false,   //分享
				flag3: false,   //没有听清楚提示
				text: '',
				index: '',    //当前点开哪个录音
				userInfo: '',  //用户信息
				id: '',  //发红包的id
				tuwen: true,   //是否是图文红包
				boss: '',   //发红包人的信息
				redInfo: '',  //红包信息
				idarr: [],  //抢了红包人的id
				yes: false,  //当抢了之后变true
				des: '',   //红包描述
				time_line: '',  //朋友圈红包分享描述
				app_message: '',  //好友红包分享描述
			},
			computed: {
				
			},
			mounted: function() {
				var that = this;
				var voice;
				var url = location.href;
				// localStorage.clear();
				if(url.indexOf('&')!=-1){
					location.href = url.split('&')[0];
				}
				this.id = this.GetQueryString("id");
				//没有带id时进入发红包
				if(this.id == null) {
					location.href = '{:U('red/send')}';
				}			
				//按下开始录音
				$('#longtap').on('touchstart', function(event){	
					event.preventDefault();
					START = new Date().getTime();
					recordTimer = setTimeout(function(){
						if(localStorage.rainAllowRecord == 'true') {
							that.flag = true;
						}				    	
						wx.startRecord({
							success: function(data){
								localStorage.rainAllowRecord = 'true';
								wx.onVoiceRecordEnd({
								    // 录音时间超过一分钟没有停止的时候会执行 complete 回调
								    complete: function (res) {
								    	var localId = res.localId; 
								    	that.flag = false;
								    }
								});
							},
							cancel: function () {
								alert('用户拒绝授权录音');
							}
						});
					},300);				    
				});				
				//松手结束录音
				$('#longtap').on('touchend',function(event){
					that.flag = false;
					event.preventDefault();
					END = new Date().getTime();
					var second = Math.ceil((END - START)/1000)
					if((END - START) < 300){
						END = 0;
						START = 0;
				        //小于300ms，不录音
				        clearTimeout(recordTimer);
				    }else{
				    	wx.stopRecord({
				    		success: function (res) {
				    			voice = res.localId;
				    			wx.uploadVoice({
				    				localId: voice, 
				    				isShowProgressTips: 1, 
				    				success: function (res) {
				    					var myserverId = res.serverId;
				    					wx.translateVoice({
					                		localId: voice, 
					                		isShowProgressTips: 1, 
					                		success: function (res) {
					                			that.clear = true;
					                			var result = res.translateResult.split('。')[0];
										    	// 发送识别结果给后台
										    	$.ajax({
										    		type: 'post',
										    		url: '{:U('red/distinguish')}',
										    		data: {
										    			content: result, // 语音识别的结果
										    			second: second,
										    			serverid: myserverId,
										    			hb_id: that.id,    //红包id
										    		},
										    		success: function(data) {
										    			if(data.code == 200) {
										    				that.text = '恭喜你,抢到红包了';
										    				that.flag3 = true;	
										    				that.boss.remain_number = that.boss.remain_number - 1;
										    				setTimeout(function() {
										    					that.flag3 = false;
										    				},1500)
										    				$('#longtap').css('display','none');
										    				that.redInfo.unshift(data.data)
										    				that.idarr.push(that.userInfo.id);
										    			}else {
										    				that.text = data.msg;
										    				that.flag3 = true;	
										    				setTimeout(function() {
										    					that.flag3 = false;
										    				},1500)
										    			}
										    		},
										    		error: function(data) {
										    			alert('没有抢到红包')
										    		}
										    	})
										    },
										    // 不能识别时
										    complete: function() {
										    	if(!that.clear) {
										    		that.flag3 = true;
										    		that.text = '没有挺清楚哦';
										    		setTimeout(function() {
										    			that.flag3 = false;
										    		},1500)
										    	}
										    }
										});
				    				}
				    			});		
				    		},
				    		fail: function (res) {
				    			
				    		}
				    	});
				    }
				});
				//注册微信播放录音结束事件【一定要放在wx.ready函数内】
				wx.onVoicePlayEnd({
					success: function (res) {
						stopWave();
					}
				});	
				// 红包领取情况
				$.ajax({
					type: 'post',
					url: '{:U('red/info')}',
					data: {
						id: that.id
					},
					success: function(data) {
						if (data.code != 200) {
							alert(data.msg);
							return false;
						}
						that.boss = data.data.red;
						that.redInfo = data.data.log;
						that.time_line = data.data.time_line;
						that.app_message = data.data.app_message;
						if(data.data.red.is_geted == 0 && data.data.red.status == 2) {
							$('#longtap').css('display','block');
						}
						// 修改描述
						if(that.boss.content == '') {
							that.des = '口令红包 说对算你赢';
						}else {
							that.des = that.boss.content;
						}
						var len = that.boss.number - that.boss.remain_number;
						for(var i=0;i<len;i++) {
							that.idarr.push(data.data.log[i].user_id)
						}
						console.log(len,that.idarr)

					},
					error: function() {

					}

				})				
				$.ajax({
					url: '{:U('setting/wxJsSDK')}',
					type: 'post',
					data: {
						url: url,
						code: 1
					},
					success: function(data) {
						// console.log(data);
						that.wxdata = data.data;
						wx.config({
							debug: false, 
							appId: that.wxdata.appId, 
							timestamp: that.wxdata.timestamp, 
							nonceStr: that.wxdata.nonceStr, 
							signature: that.wxdata.signature,
							jsApiList: [
							"onMenuShareTimeline",   
							"onMenuShareAppMessage", 
							"startRecord",    
							"stopRecord",     
							"onVoiceRecordEnd", 
							"playVoice",       
							"uploadVoice",     
							"downloadVoice",
							"translateVoice"
							] 
						});

						wx.ready(function(){
							// 获取用户信息
							$.ajax({
								url: '{:U('user/info')}',
								type: 'post',
								data: {},
								success: function(data) {
									if(data.code == 200) {
										that.userInfo = data.data;
									}else {
										alert(data.msg)
									}
								},
								error: function() {

								}
							})
							// 在第一次按住录音后，由于用户未曾允许录音，微信会提示用户授权允许在本页面使用微信录音功能，这时用户会放开录音按钮转而去点击允许，在用户允许后，才真正会开始录音，而此时用户早已放开录音按钮，那么录音按钮上便不会再有touchend事件，录音便会一直进行。
							// 解决策略：使用localStorage记录用户是否曾授权，并以此来判断是否需要在刚进入页面是自动录一段录音来触发用户授权
							if(!localStorage.rainAllowRecord || localStorage.rainAllowRecord !== 'true'){
								wx.startRecord({
									success: function(){
										localStorage.rainAllowRecord = 'true';
										wx.stopRecord({
											success: function (res) {}
										});
									},
									cancel: function () {
										alert('用户拒绝授权录音');
									}
								});
							}
							wx.onMenuShareAppMessage({
								title: that.app_message.title, 
								desc: that.app_message.desc, 
								link: that.app_message.link, 
								imgUrl: that.app_message.imgUrl,  
								type: '', 
								dataUrl: '', 
								success: function () { 
									that.flag2 = false;
									// that.todo(); 
									that.text = '分享成功';
									that.flag3 = true;
						    		setTimeout(function() {
						    			that.flag3 = false;
						    		},1500)
								},
								cancel: function () { 
									
								}
							});
							wx.onMenuShareTimeline({
								title: that.time_line.title, 
								link: that.time_line.link, 
								imgUrl: that.time_line.imgUrl, 
								success: function () { 
									that.text = '分享成功';
									that.flag3 = true;
						    		setTimeout(function() {
						    			that.flag3 = false;
						    		},1500)
								},
								cancel: function () { 
									
								}
							});
						});
						wx.error(function(res){
							alert("调用失败")
						});
					},
					error: function() {

					}
				})		
			},
			methods: {
				GetQueryString(name){
					var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
					var r = window.location.search.substr(1).match(reg);
					if(r!=null)return  decodeURI(r[2]); return null;
				},
				To: function(url) {
					location.href = url;
				},
				toSay: function(url) {
					$('#audio')[0].src = 'http://sfmhb.shanfengmao.com/' + url; 
					$('#audio')[0].play();
				},
				share: function() {
					this.flag2 = true;
				},
				todo: function() {
					var that = this;
					$.ajax({
						type: 'post',
						url: '/Common/shareLog',
						data: {
							id: that.userInfo.id,
							name: that.userInfo.nickname
						},
						success: function() {

						},
						error: function() {

						}
					})
				}
			},
			filters:{
				toFixed:function (price) {
					return Number(price).toFixed(2);
				},
				time:function (time) {
					var time2 = time.substr(5);
					var time2 = time2.split('-').join('月').split(' ').join('日 ');
					return time2;
				},
				str: function(str) {
					return str+'″';
				}
			}
		})
	</script>
</body>
</html>